package com.mhc.suzuki.service.impl;

import com.mhc.haval.security.model.User;
import com.mhc.suzuki.bo.SubmitTaskBO;
import com.mhc.suzuki.constant.*;
import com.mhc.suzuki.dal.mapper.ext.*;
import com.mhc.suzuki.dal.model.*;
import com.mhc.suzuki.dal.query.*;
import com.mhc.suzuki.exception.SuzukiCommonException;
import com.mhc.suzuki.manager.*;
import com.mhc.suzuki.service.ModificationService;
import com.mhc.suzuki.service.ModifyService;
import com.mhc.suzuki.service.SubmitTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HW
 * on 2017/9/4 15:39.
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class ModificationServiceImpl  implements ModificationService{

    @Autowired
    private OrderManager orderManager;

    @Autowired
    private OrderCustomerRelManager orderCustomerRelManager;

    @Autowired
    private HouseInfoManager houseInfoManager;

    @Autowired
    private CustomerManager customerManager;

    @Autowired
    private EmergencyContactManager emergencyContactManager;

    @Autowired
    private SubmitTaskService submitTaskService;

    @Autowired
    private ModifyService modifyService;

    @Autowired
    private CreditQueryApplyManager creditQueryApplyManager;

    @Autowired
    private AnnexListExtMapper annexListExtMapper;

    /**
     * 申请互换购车人
     * @param orderNo
     * @param reason 原因
     * @param user 当前操作用户
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean buyerReplacement(String orderNo, String reason, User user) throws SuzukiCommonException{
        if(StringUtils.isBlank(orderNo)){
            return false;
        }

        boolean result = true;

        /*根据订单号查询对应订单*/
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.createCriteria().andOrderNoEqualTo(orderNo)
                                .andOrderStatusNotEqualTo(OrderStatusEnum.CANCELLED.getCode());
        List<OrderDO> orderDOS = orderManager.selectByQuery(orderQuery);
        if(orderDOS.size() != 1) {
            throw new SuzukiCommonException(ErrorCodeEnum.NO_DATA);
        }

        //修改具体表数据
        if(!exchangeBuyer(orderNo)){
            throw  new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }

        Integer status = orderDOS.get(0).getOrderStatus();

        //贷款审核通过前
        if(OrderStatusEnum.CREDITING.getCode().equals(status) || OrderStatusEnum.CREDIT_HAS_BEEN_RECORDER.getCode().equals(status)){//贷款审核中撤销订单进行更换操作
            return true;
        } else if (!OrderStatusEnum.CREDITING.getCode().equals(status)  &&  !OrderStatusEnum.CREDIT_HAS_BEEN_RECORDER.getCode().equals(status)&& !OrderStatusEnum.UNDER_REVIEW.getCode().equals(status)){

            //调用修改流程
            SubmitTaskBO submitTaskBO = new SubmitTaskBO();
            submitTaskBO.setBizType(orderDOS.get(0).getBizChannel());
            submitTaskBO.setOrderNo(orderNo);
            submitTaskBO.setApplyType(ApplyTypeEnum.MODIFY_APPLY.getCode());
            submitTaskBO.setRemark(reason);
            if(submitTaskService.updateApply(submitTaskBO, user)){
                throw  new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
            }
            //存入修改历史信息
            modifyService.createModify(EntityTypeEnum.ORDER.getCode(), orderNo, user.getStaffId());

        } else {//订单为其他状态，数据有误
            log.error(status + "is not allowed to exchangeBuyer");
            throw new SuzukiCommonException(ErrorCodeEnum.DATA_ERROR);
        }


        return result;
    }


    /**
     * 更换主贷人数据库操作
     * @param orderNo 订单编号
     * @return boolean 更换操作是否成功
     * @throws Exception 运行错误
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean exchangeBuyer(String orderNo) throws SuzukiCommonException {

        /*互换购车人及共同购车人与订单关系*/
        /*条件控制*/
        Map<String, Object> map = new HashMap<>(64);
        map.put("BUYER", CustomerTypeEnum.BUYER.getCode());
        map.put("COMMONBUYER", CustomerTypeEnum.COMMONBUYER.getCode());
        map.put("orderNo", orderNo);
        map.put("isDeleted", IsDeletedEnum.NORMAL.getCode());
        int count = orderCustomerRelManager.exchangeBuyer(map);

        if(count != 2){
            log.error("exchangeBuyer failed");
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }

        /*查询关系互换后订单对应customer*/

        //更换后购车人,即之前共同购车人
        CustomerDO buyer = customerManager.getExchangedBuyer(map);
        //更换后共同购车人, 即之前购车人
        CustomerDO commonBuyer = customerManager.getExchangedCommonBuyer(map);

        /*更改对应订单信息*/
        OrderQuery orderQuery = new OrderQuery();
        orderQuery.createCriteria()
                .andOrderNoEqualTo(orderNo)
                .andOrderStatusNotEqualTo(OrderStatusEnum.CANCELLED.getCode())
                .andCustomerIdEqualTo(commonBuyer.getCustomerId());

        OrderDO orderDO = new OrderDO();
        orderDO.setCustomerId(buyer.getCustomerId());
        orderDO.setCustomerIdCard(buyer.getIdCard());
        orderDO.setCustomerName(buyer.getCustomerName());

        if(orderManager.updateByQuerySelective(orderDO, orderQuery) != 1){
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }

        /*更改房产对应信息*/
        HouseInfoQuery houseInfoQuery = new HouseInfoQuery();
        houseInfoQuery.createCriteria()
                .andCustomerIdEqualTo(commonBuyer.getCustomerId());

        HouseInfoDO houseInfoDO = new HouseInfoDO();
        houseInfoDO.setCustomerId(buyer.getCustomerId());//更改id
        houseInfoDO.setCustomerName(buyer.getCustomerName());//更改姓名

        if(houseInfoManager.updateByQuerySelective(houseInfoDO, houseInfoQuery) > 1 ){
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }


        /*更换紧急联系人相关信息*/
        EmergencyContactQuery emergencyContactQuery = new EmergencyContactQuery();
        emergencyContactQuery.createCriteria()
                .andCustomerIdEqualTo(commonBuyer.getCustomerId());

        EmergencyContactDO emergencyContactDO = new EmergencyContactDO();
        emergencyContactDO.setCustomerId(commonBuyer.getCustomerId());

        int i = emergencyContactManager.updateByQuerySelective(emergencyContactDO, emergencyContactQuery);
        if ( i < 0 || i > 2){
            throw new SuzukiCommonException(ErrorCodeEnum.INSERT_OR_UPDATA_ERROR);
        }


        //更换附件批次分组
        changeAnnexGroup(buyer.getCustomerId(), AnnexGroupEnum.BUYER.getCode());
        changeAnnexGroup(commonBuyer.getCustomerId(), AnnexGroupEnum.COMMONBUYER.getCode());

        return true;
    }

    /**
     * 更换附件批次分组
     * @param custommerId
     * @param annexGroup
     */
    private void changeAnnexGroup(Long custommerId, Integer annexGroup) throws SuzukiCommonException{
        //更换附件批次号分组
        //更换后购车人
        OrderCustomerRelQuery orderCustomerRelQueryBuyer = new OrderCustomerRelQuery();
        orderCustomerRelQueryBuyer.createCriteria().andCustomerIdEqualTo(custommerId)
                .andIsDeletedNotEqualTo(IsDeletedEnum.DELETED.getCode());
        List<OrderCustomerRelDO> orderCustomerRelDOBuyers =  orderCustomerRelManager.selectByQuery(orderCustomerRelQueryBuyer);
        if (orderCustomerRelDOBuyers.size() != 1){
            throw new SuzukiCommonException(ErrorCodeEnum.SYS_ERROR);
        }

        OrderCustomerRelDO orderCustomerRelDOBuyer = orderCustomerRelDOBuyers.get(0);
        //更换后购车人征信查询申请编号
        Long  creditIdBuyer = orderCustomerRelDOBuyer.getCreditApplyId();

        CreditQueryApplyQuery creditQueryApplyQuery = new CreditQueryApplyQuery();
        creditQueryApplyQuery.createCriteria().andCreditQueryApplyIdEqualTo(creditIdBuyer);

        List<CreditQueryApplyDO> creditQueryApplyDOS = creditQueryApplyManager.selectByQuery(creditQueryApplyQuery);
        if (creditQueryApplyDOS.size() != 1){
            throw new SuzukiCommonException(ErrorCodeEnum.SYS_ERROR);
        }

        CreditQueryApplyDO creditQueryApplyDO = creditQueryApplyDOS.get(0);
        //获取附件批次号
        String annexNo = creditQueryApplyDO.getAnnexBatchNo();

        //更新附件批次分组
        AnnexListDO annexListDO = new AnnexListDO();
        annexListDO.setAnnexGroup(annexGroup);
        AnnexListQuery annexListQuery = new AnnexListQuery();
        annexListQuery.createCriteria().andAnnexBatchNoEqualTo(annexNo);
        annexListExtMapper.updateByQuerySelective(annexListDO, annexListQuery);
    }
}
